const publish = require('../models/publish')
const users = require('../models/users')
const course = require('../models/course')
const studentWork = require('../models/studentWork')
const teamWork = require('../models/teamWork')
const formidable = require('formidable')
const node_xlsx = require('node-xlsx')
const fs = require('fs')
const send = require('koa-send')
const archiver = require('archiver')
/****
 * 
 * 发布作业
 * 
 */
var publishTask=async(ctx,next)=>{
    var creatWork = async function(newPath,publish_Data){
        var document = await publish.findOne({workName:publish_Data.workName,course:publish_Data.course})
        console.log(document)
        if(document){
            var D_id = document._id;
            await publish.findByIdAndUpdate(D_id,{$set:{endTime:publish_Data.endTime,workDetails:publish_Data.workDetails,accessory:newPath,isTeam:publish_Data.isTeam}},function(err,res){
                console.log(err);
            })
            if(!document.isTeam==publish_Data.isTeam){
                if(publish_Data.isTeam){
                    await studentWork.remove({workName:publish_Data.workName,course:publish_Data.course});
                    var teamArr = await teamWork.find({course:publish_Data.course})
                    var Ojson = {
                        workName:publish_Data.workName,
                        startTime:publish_Data.startTime||Date.now(),
                        endTime:publish_Data.endTime||"",
                        accessory:"",
                        workStatus:1,
                        score:""
                    }
                    for(var i=0;i<teamArr.length;i++){
                        await teamWork.findByIdAndUpdate(teamArr[i]._id,{$push:{work:Ojson}},function(err,res){
                            console.log(err);
                        })
                    }
                }else{
                    var teamArr = await teamWork.find({course:publish_Data.course})
                    for(var i=0;i<teamArr.length;i++){
                        await teamWork.findByIdAndUpdate(teamArr[i]._id,{$pull:{work:{workName:publish_Data.workName,}}},function(err,res){
                            console.log(err);
                        })
                    }
                    var oCourse = await course.findOne({course:publish_Data.course});
                    var stuArr = oCourse.student;
                    for(var i=0;i<stuArr.length;i++){
                        var student = await users.findOne({userID:stuArr[i]});
                        var studentWorkEntity = new studentWork({
                            studentID:student.userID,
                            name:student.userName,
                            workName:publish_Data.workName,
                            course:publish_Data.course,
                            startTime:publish_Data.startTime||Date.now(),
                            endTime:publish_Data.endTime||""
                        })
                        studentWorkEntity.save(function(err,doc){
                            if(err){
                                console.log(err);
                            }else{
                                console.log(doc);
                            }
                        })
                    }
                }
            }     
        }else{
            console.log("开始创建作业")
            var publishEntity = new publish({
                workName:publish_Data.workName,
                course:publish_Data.course,
                startTime:publish_Data.startTime||Date.now(),
                endTime:publish_Data.endTime||"",
                workDetails:publish_Data.workDetails||"",
                accessory:newPath,
                isTeam:publish_Data.isTeam,
            })
            await publishEntity.save(function(err,doc){
                if(err){
                    console.log(err);
                }else{
                    console.log(doc);
                }
            })
            if(publish_Data.isTeam==2){
                console.log("开始创建团队作业")
                var teamArr = await teamWork.find({course:publish_Data.course})
                var Ojson = {
                    workName:publish_Data.workName,
                    startTime:publish_Data.startTime||Date.now(),
                    endTime:publish_Data.endTime||"",
                    accessory:"",
                    workStatus:1,
                    score:"",
                    submitTime:"",
                    evaluate:""
                }
                for(var i=0;i<teamArr.length;i++){
                    await teamWork.findByIdAndUpdate(teamArr[i]._id,{$push:{work:Ojson}},function(err,res){
                        console.log(err);
                    })
                }
            }else if(publish_Data.isTeam==1){
                console.log("开始创建个人作业")
                var oCourse = await course.findOne({course:publish_Data.course});
                var stuArr = oCourse.student;
                for(var i=0;i<stuArr.length;i++){
                    var student = await users.findOne({userID:stuArr[i]});
                    var studentWorkEntity = new studentWork({
                        studentID:student.userID,
                        name:student.userName,
                        workName:publish_Data.workName,
                        course:publish_Data.course,
                        startTime:publish_Data.startTime||Date.now(),
                        endTime:publish_Data.endTime||""
                    })
                    await studentWorkEntity.save(function(err,doc){
                        if(err){
                            console.log(err);
                        }else{
                            console.log(doc);
                        }
                    })
                }
            }
        }
        console.log("成功")
        return 'success'
    }
    var fileParse = async function(){
        var form = new formidable.IncomingForm();
            form.encoding = 'utf-8';
            form.uploadDir = './upload/work/';
            form.keepExtensions = true;
            form.maxFieldsSize = 2*1024*1024; 
        return new Promise((resolve,reject)=>{
            form.parse(ctx.req,async function(err,fields,files){
                if(err){
                    console.log(form);
                    console.log(err);
                    return;
                }
                var is = await fs.existsSync('./upload/work/'+fields.course)
                if(!is){
                    await fs.mkdir('./upload/work/'+fields.course,function(err){
                        if(err){
                            console.log(err);
                        }
                    })
                }
                var fileName = files.fileName.name;
                var isfile = await fs.existsSync('./upload/work/'+fields.course+'/'+fileName)
                if(isfile){
                    await fs.unlink('./upload/work/'+fields.course+'/'+fileName,function(err){
                        console.log(err);
                    })
                }
                var newPath = form.uploadDir+fields.course+'/'+fileName;
                console.log(newPath);
                await fs.renameSync(files.fileName.path,newPath);
                console.log("重命名成功")
                ////////////////////
                var res1= await creatWork(newPath,fields);
                if(res1=='success'){
                    var document = publish.findOne({course:fields.course,workName:fields.workName})
                    resolve(document)
                }
                
            })
        })
    }
    //////////////////
    var res = await fileParse();
    ctx.response.body = {stauts:'success',msg:'发布成功',res};
    

}
 /**
  * 
    获取实验信息

  */
  var getpublish = async(ctx,next)=>{
    //通用信息
    var oPublish = await publish.find({course:ctx.request.body.course}).sort({"endTime":1});
    //以下为学生页面需要的信息
    var oCourse = await course.findOne({course:ctx.request.body.course});
    console.log(oCourse);
    var user = await users.findOne({userID:oCourse.teacher})
    user.password = null;
    var team = await teamWork.findOne({teamMember:ctx.request.body.userID,course:ctx.request.body.course})
    var member = new Array();
    if(team){
        for(var i=0;i<team.teamMember.length;i++){
            var memberName = await users.findOne({userID:team.teamMember[i]})
            member.push(memberName.userName)
        }
    }
    ctx.response.body = {stauts:'success',msg:'获取成功',oPublish,oCourse,user,team,member};
}
  
 /**
  * 
    下载作业附件
    workName，course

  */
var download = async(ctx,next)=>{
    var document = await publish.findOne({workName:ctx.params.workName,course:ctx.params.course})
    if(document.accessory==""){
         return ctx.response.body = {stauts:'error',msg:'该作业没有附件'};
    }
    var fileName = document.accessory.substring(document.accessory.lastIndexOf("/")+1,document.accessory.length);
    var path = document.accessory;
    ctx.attachment(fileName);
    await send(ctx, path);
}
/**
 * 
 * 删除作业
 * workName，course
 */
var pullStudent = async(ctx,next)=>{
    let document= await publish.findOne({course:ctx.request.body.course,workName:ctx.request.body.workName});
    if(document){
        await publish.findByIdAndRemove(document._id);
        if(document.isTeam==1){
            console.log("删除个人作业")
            await studentWork.remove({course:ctx.request.body.course,workName:ctx.request.body.workName})
        }else if(document.isTeam==2){
            console.log("删除团队作业")
            var team = await teamWork.find({course:ctx.request.body.course})
            for(var i=0;i<team.length;i++){
                await teamWork.findByIdAndUpdate(team[i]._id,{$pull:{work:{workName:ctx.request.body.workName}}})
            }
        }
    }else{
        return ctx.response.body = {stauts:'error',msg:'作业不存在'};
    }
    
}
 /**
  * 
    下载全部作业
    workName，course

  */
  var downloadAll = async(ctx,next)=>{
    var zipName = ctx.params.workName+'.zip';
    var path = './upload/zip/'+zipName
    var zipStream = await fs.createWriteStream(path);
    var zip = archiver('zip')
    await zip.pipe(zipStream);
    await zip.directory('./upload/work/'+ctx.params.course+'/'+ctx.params.workName+'/',ctx.params.workName)
    await zip.finalize()
    ctx.attachment(zipName);
    await send(ctx,path);
}
module.exports = {
    'POST /publish/publishTask': publishTask,
    'POST /publish/getpublish': getpublish,
    'GET /publish/download/:workName/:course': download,
    'POST /publish/pullStudent': pullStudent,
    'GET /publish/downloadAll/:workName/:course': downloadAll,
}